<template>
  <div>
    <TopFilter ref="topFilter" :list="topFilterList" :cols="4" @filterChange="changeHandle" @onCollapse="collapseHandle" />
    <FilterTable
      ref="lackDetailTable"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      columnsRef="partPartOtherLackDetailIndex"
      :datakey="'rows'"
      :onRowSelectChange="columns => (this.partColumns = columns)"
      :onColumnsChange="columns => (this.columns = columns)"
      :onSyncTableData="dataHandle"
      :isExportExcel="true"
      :onCalcExportData="exportFun"
      exportFileName="配件缺料明细.xlsx"
    >
      <template slot="controls">
        <el-button size="small" type="primary" icon="el-icon-plus" @click="hanldeAddNewLack" v-show="false">新建</el-button>
        <el-button size="small" type="primary" @click="saveClick">保存</el-button>
        <el-button size="small" type="primary" @click="exportClick">导出</el-button>
        <!-- <el-button size="small" type="primary" :loading="outputBtnLoading" icon="el-icon-download" @click="exportClick">导出</el-button> -->
      </template>
    </FilterTable>

    <!-- 新增欠料单明细 -->
    <BaseDialog
      width="80%"
      :visible.sync="addNewLackVisible"
      :title="`${addPanelType == 'add' ? '新增' : '编辑'}缺料单`"
      destroyOnClose
      :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }"
    >
      <addLackDetail :type="addPanelType" :shortId="editShortId" @close="addNewLackVisible = false" @researchTableData="handleResearchTableData" />
    </BaseDialog>
  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import { exportExcelFile, camelCaseObject } from '@/utils';
import { queryShortPart, saveShortPart, exportData } from '@/api/part/partOther/lackDetail';
import { findAllRepair } from '@/api/repair/basicParameters';
import { getStroageList } from '@/api/part/partOutbound/partBreak';
import { getAllUser } from '@/api/customerRepair/afterSaleVisit/resultEntry';
import dictCode from '@/utils/dictCode';
import moment from 'moment';
import addLackDetail from './addLackDetail';

export default {
  name: 'lackDetail',
  components: {
    addLackDetail
  },
  mixins: [dictionary],
  data() {
    return {
      topFilterList: this.createTopFilterList(),
      fetchParams: { xhrAbort: true },
      columns: this.createTableColumns(),
      fetchApi: queryShortPart,
      partColumns: [],
      serviceAdvisorData: [],
      addNewLackVisible: false,
      outputBtnLoading: false,
      addPanelType: 'add', // 弹窗类型(add,edit)
      editShortId: '' // 编辑的单代码
    };
  },
  mounted() {
    this.getQueryBookingInformation();
    this.BaseTable = this.$refs.lackDetailTable.$refs.pageTable;
    this.getStorage();
  },
  methods: {
    // 导出数据处理
    exportFun(row) {
      for (const key in row) {
        if (row.hasOwnProperty(key)) {
          let element = row[key];
          switch (key) {
            case 'UPDATED_BY':
            case 'SERVICE_PERSON':
              row[key] = this.getEmployeeName(row[key]);
              break;
            case 'MAJOR_PERSON':
              row[key] = this.getEmployeeName(row[key]);
              break;
            case 'HANDLER':
              row[key] = this.getEmployeeName(row[key]);
              break;
            case 'CREATED_BY':
              row[key] = this.getEmployeeName(row[key]);
              break;
            case 'CREATED_AT':
              if (row[key]) {
                row[key] = moment(row[key]).format('YYYY-MM-DD');
              }
              break;
            case 'IN_DATE':
              if (row[key]) {
                row[key] = moment(row[key]).format('YYYY-MM-DD');
              }
              break;
            case 'RO_DATE':
              if (row[key]) {
                row[key] = moment(row[key]).format('YYYY-MM-DD');
              }
              break;
            default:
              break;
          }
        }
      }
    },
    dataHandle(val) {
      // val.forEach(x => {
      //   // if (x.CLOSE_STATUS == 80601001) {
      //   //   x.CLOSE_STATUS = 10041001;
      //   // } else if (x.CLOSE_STATUS == 80601002) {
      //   //   x.CLOSE_STATUS = 10041002;
      //   // }
      //   // 需求数量 = 库存数量 + 缺料数量
      //   x.COMPUTED_SHORT_QUANTITY = x.SHORT_QUANTITY + (x.STOCK_QUANTITY || 0);
      // });
      // console.log(val);
    },
    createTopFilterList() {
      return [
        {
          type: 'SELECT',
          label: '仓库',
          fieldName: 'STORAGE_CODE',
          placeholder: '请选择...',
          itemList: []
        },
        {
          type: 'INPUT',
          label: '单据号码',
          fieldName: 'SHEET_NO',
          placeholder: '请输入...'
        },
        {
          type: 'INPUT',
          label: '配件代码',
          fieldName: 'PART_NO',
          placeholder: '请输入...'
        },
        // {
        //     type: 'SELECT',
        //     label: '工单类型',
        //     fieldName: 'roType',
        //     placeholder: '请选择工单类型',
        //     itemList: this.createDictList('8049')
        // },
        {
          type: 'SELECT',
          label: '缺料类型',
          fieldName: 'SHORT_TYPE',
          placeholder: '请选择...',
          itemList: this.createDictList('8134'),
          showOverflowTooltip: true
        },
        {
          type: 'RANGE_DATE',
          label: '缺料日期',
          fieldName: 'BOOK_BEGIN_DATE|BOOK_END_DATE',
          // placeholder: '请选择缺料日期',
          initialValue: [`${moment().get('year')}-${moment().get('month') + 1}-01`, moment().format('YYYY-MM-DD')],
          valueFormat: 'yyyy-MM-dd'
        },
        {
          type: 'SELECT',
          label: '结案状态',
          fieldName: 'CLOSE_STATUS',
          placeholder: '请选择...',
          itemList: this.createDictList('1004')
        }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '操作',
          dataIndex: 'operation',
          stopRowSelection: true,
          fixed: 'left',
          render: params => {
            return (
              <el-button
                type="text"
                onClick={() => {
                  this.handleEdit(params.row);
                }}
              >
                编辑
              </el-button>
            );
          }
        },
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          render: props => {
            return <span>{props.row.$index + 1}</span>;
          }
        },
        // {
        //   title: '欠料明细描述',
        //   dataIndex: 'REMARKS',
        //   showOverflowTooltip: true,
        //   filter: true,
        //   filterType: 'input'
        // },
        // {
        //   title: '是否急件',
        //   dataIndex: 'IS_URGENT',
        //   width: 120,
        //   editable: true,
        //   defaultEditable: true,
        //   editType: 'select',
        //   disabled: false,
        //   editItems: [
        //     { text: '是', value: 10041001 },
        //     { text: '否', value: 10041002 }
        //   ],
        //   sorter: true,
        //   filter: true,
        //   filterType: 'checkbox',
        //   filterItems: this.createDictList('1004'),
        //   showOverflowTooltip: true
        // },
        {
          title: '是否已结案',
          dataIndex: 'CLOSE_STATUS',
          editable: true,
          disabled: false,
          defaultEditable: true,
          editType: 'select',
          editItems: [
            { text: '是', value: 10041001 },
            { text: '否', value: 10041002 }
          ],
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('1004'),
          showOverflowTooltip: true
        },
        {
          title: '仓库',
          dataIndex: 'STORAGE_NAME',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '库位代码',
          dataIndex: 'STORAGE_POSITION_CODE',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '缺料类型',
          dataIndex: 'SHORT_TYPE',
          width: 150,
          render: props => {
            return <span>{this.createDictText(props.row.SHORT_TYPE, '8134')}</span>;
          },
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('8134'),
          dictItems: this.createDictList('8134'),
          showOverflowTooltip: true
        },
        {
          title: '配件代码',
          dataIndex: 'PART_NO',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '配件名称',
          dataIndex: 'PART_NAME',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '单据号码',
          dataIndex: 'SHEET_NO',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '车牌号',
          dataIndex: 'LICENSE',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '当前库存量',
          dataIndex: 'STOCK_QUANTITY',
          sorter: true,
          filter: true,
          filterType: 'number',
          showOverflowTooltip: true
        },
        {
          title: '缺料数量',
          dataIndex: 'SHORT_QUANTITY',
          filterType: 'number',
          sorter: true,
          filter: true,
          filterType: 'number',
          showOverflowTooltip: true
        },
        {
          title: '客户名称',
          dataIndex: 'CUSTOMER_NAME',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        // {
        //   title: '电话',
        //   width: 100,
        //   dataIndex: 'PHONE',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input',
        //   showOverflowTooltip: true
        // },
        {
          title: '缺料时间',
          dataIndex: 'CREATED_AT',
          dateFormat: 'yyyy-MM-dd',
          sorter: true,
          filter: true,
          filterType: 'date-range',
          showOverflowTooltip: true
        },
        {
          title: '经手人',
          dataIndex: 'HANDLER',
          // render: props => {
          //   return <span>{this.getEmployeeName(props.row.HANDLER)}</span>;
          // },
          sorter: true,
          // filter: true,
          filterType: 'checkbox',
          filterItems: [],
          dictItems: [],
          showOverflowTooltip: true
        }
        // {
        //   title: '出入库类型',
        //   dataIndex: 'IN_OUT_TYPE',
        //   render: props => {
        //     return <span>{this.createDictText(props.row.IN_OUT_TYPE, '8249')}</span>;
        //   },
        //   sorter: true,
        //   filter: true,
        //   filterType: 'checkbox',
        //   filterItems: this.createDictList('8249'),
        //   dictItems: this.createDictList('8249'),
        //   showOverflowTooltip: true
        // },

        // {
        //   title: '需求数量',
        //   dataIndex: 'SHORT_QUANTITY',
        //   filterType: 'number',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'number',
        //   showOverflowTooltip: true
        // },

        // {
        //   title: '订货状态',
        //   dataIndex: 'ORDER_GOODS_STATUS',
        //   filter: true,
        //   filterType: 'checkbox',
        //   filterItems: this.createDictList(1004),
        //   dictItems: this.createDictList(1004)
        // },
        // {
        //   title: '到货日期',
        //   dataIndex: 'IN_DATE',
        //   dateFormat: 'yyyy-MM-dd',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'date-range',
        //   showOverflowTooltip: true
        // },
        // {
        //   title: '维修日期',
        //   dataIndex: 'RO_DATE',
        //   dateFormat: 'yyyy-MM-dd',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'date-range',
        //   showOverflowTooltip: true
        // },
        // {
        //   title: '服务顾问',
        //   dataIndex: 'SERVICE_PERSON',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'checkbox',
        //   filterItems: [],
        //   dictItems: [],
        //   showOverflowTooltip: true
        //   // render: props => {
        //   //   return <span>{this.getEmployeeName(props.row.SERVICE_PERSON)}</span>;
        //   // }
        // },
        // {
        //   title: '主修人',
        //   dataIndex: 'MAJOR_PERSON',
        //   // render: props => {
        //   //   return <span>{this.getEmployeeName(props.row.MAJOR_PERSON)}</span>;
        //   // },
        //   sorter: true,
        //   filter: true,
        //   filterType: 'checkbox',
        //   filterItems: [],
        //   dictItems: [],
        //   showOverflowTooltip: true
        // },

        // {
        //   title: '创建人',
        //   dataIndex: 'CREATED_BY',
        //   // render: props => {
        //   //   return <span>{this.getEmployeeName(props.row.CREATED_BY)}</span>;
        //   // },
        //   sorter: true,
        //   filter: true,
        //   filterType: 'checkbox',
        //   filterItems: [],
        //   dictItems: [],
        //   showOverflowTooltip: true
        // },
        // {
        //   title: '修改人',
        //   dataIndex: 'UPDATED_BY',
        //   // render: props => {
        //   //   return <span>{this.getEmployeeName(props.row.UPDATED_BY)}</span>;
        //   // },
        //   sorter: true,
        //   filter: true,
        //   filterType: 'checkbox',
        //   filterItems: [],
        //   dictItems: [],
        //   showOverflowTooltip: true
        // }
      ];
    },
    // 重新查询主列表数据
    handleResearchTableData() {
      this.fetchParams.xhrAbort = true;
      this.fetchParams.xhrAbort = false;
    },
    async getQueryBookingInformation() {
      let res = await getAllUser();
      this.serviceAdvisorData = res.data.map(x => ({ text: x.employeeName, value: x.userId + '' }));
      this.columns.find(x => x.dataIndex == 'HANDLER').dictItems = this.serviceAdvisorData;
      this.columns.find(x => x.dataIndex == 'HANDLER').filterItems = this.serviceAdvisorData;
      let serviceAdvisorNameList = ['HANDLER'];
      serviceAdvisorNameList.forEach(item => {
        this.columns.find(item2 => item2.dataIndex === item).dictItems = this.columns.find(item2 => item2.dataIndex === item).filterItems = this.serviceAdvisorData;
      });
    },
    getEmployeeName(userId) {
      const item = this.serviceAdvisorData.find(x => {
        return x.value == userId;
      });
      return item ? item.text : '';
    },
    // 查询仓库信息
    async getStorage() {
      const res = await getStroageList();
      // let resdata = await findAllRepair();
      this.topFilterList.find(item => item.fieldName === 'STORAGE_CODE').itemList = res.data.map(x => ({ text: x.STORAGE_NAME, value: x.STORAGE_CODE }));
      // this.topFilterList.find(item => item.fieldName === 'STORAGE_CODE').initialValue = resdata.data['1100'];
    },
    changeHandle(val) {
      this.fetchParams.xhrAbort = true;
      this.fetchParams = Object.assign(this.fetchParams, val, {
        BOOK_BEGIN_DATE: val.BOOK_END_DATE ? val.BOOK_BEGIN_DATE.split(' ')[0] : '',
        BOOK_END_DATE: val.BOOK_END_DATE ? val.BOOK_END_DATE.split(' ')[0] : '',
        xhrAbort: false
      });
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    // 点击新建缺料单
    hanldeAddNewLack() {
      this.addPanelType = 'add';
      this.addNewLackVisible = true;
    },
    // 点击编辑
    handleEdit(e) {
      console.log(e);
      this.addPanelType = 'edit';
      this.editShortId = e.SHORT_ID;
      this.addNewLackVisible = true;
    },
    // 导出点击事件
    async exportClick() {
      // if (this.partColumns.length <= 0) {
      //   return this.$notify.error({ title: '提示信息', message: '请选择一条数据' });
      // }
      if (this.outputBtnLoading) return;
      this.outputBtnLoading = true;
      let searchParams = await this.$refs.topFilter.GET_FORM_DATA();
      let res = await exportData(searchParams[1]);
      this.outputBtnLoading = false;
      exportExcelFile(res.data, '缺料明细');
    },
    async saveClick() {
      if (this.partColumns.length <= 0) {
        this.$notify.error({ title: '提示信息', message: '请选择一条数据' });
      } else {
        let obj = {
          tableList: this.partColumns
        };
        const res = await saveShortPart(obj);
        this.fetchParams = Object.assign({}, this.fetchParams); // 刷新表格
        if ((res.resultCode = 200)) {
          this.$notify({
            title: '提示',
            message: '保存成功',
            type: 'success'
          });
        }
      }
    }
  }
};
</script>

<style lang="less" scoped></style>
